using EnvDTE;
using Microsoft.Practices.RecipeFramework;

namespace PrismFactory.SoftwareFactory.Extensions.Actions.VisualStudio
{
    /// <summary>
    /// Action that sets a global variable with a given value.
    /// </summary>
    public class SetGlobalValueAction : ConfigurableAction
    {
        private object oldValue;

        [Input(Required = true)]
        public string GlobalVariableName { get; set; }

        [Input]
        public bool PersistValue { get; set; }

        [Input(Required = true)]
        public object Value { get; set; }

        private object SetValue(object value)
        {
            var dte = (DTE) GetService(typeof (DTE));
            oldValue = null;
            if (dte.Solution.Globals.VariableExists[GlobalVariableName])
            {
                oldValue = dte.Solution.Globals[GlobalVariableName];
            }
            if (value != null)
            {
                dte.Solution.Globals[GlobalVariableName] = value.ToString();
                dte.Solution.Globals.VariablePersists[GlobalVariableName] = PersistValue;
            }
            return oldValue;
        }

        public override void Execute()
        {
            oldValue = SetValue(Value);
        }

        public override void Undo()
        {
            SetValue(oldValue);
        }
    }
}